package com.tokenmaster.aitrade.market.okex;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.tokenmaster.aitrade.common.system.IndexConfig;
import com.tokenmaster.aitrade.common.system.KLinePoint;
import com.tokenmaster.aitrade.common.system.Order_Future;
import com.tokenmaster.aitrade.market.okex.future.IFutureRestApi;
import com.tokenmaster.aitrade.market.okex.future.OkexFutureRest;

/**
 * 期货 REST API 客户端请求
 *
 * @author buxinyun
 */
public class Market_Okex_Future {

    private static Market_Okex_Future instance = new Market_Okex_Future();

    public static Market_Okex_Future getInstance() {
        return instance;
    }

    // OKCoin申请的apiKey
    String api_key = "";
    // OKCoin申请的secretKey
    String secret_key = "";
    // 注意：请求URL 国际站https://www.okcoin.com 国内站https://www.okcoin.cn
    String url_prex = "https://www.okex.com";

    /**
     * get请求无需发送身份认证,通常用于获取行情，市场深度等公共信息
     */
    IFutureRestApi iFutureGetApi = new OkexFutureRest(url_prex);

    /**
     * post请求需发送身份认证，获取用户个人相关信息时，需要指定api_key,与secret_key并与参数进行签名，
     * 此处对构造方法传入api_key与secret_key,在请求用户相关方法时则无需再传入， 发送post请求之前，程序会做自动加密，生成签名。
     */
    IFutureRestApi iFuturePostApi = new OkexFutureRest(url_prex, api_key, secret_key);

    public double getTicker(String symbol, String contract_type) throws IOException {
        // 期货行情信息
        String tickerStr_Future = iFutureGetApi.future_ticker(symbol, contract_type);

        JSONObject jsonObject = JSONObject.parseObject(tickerStr_Future);
        JSONObject jsonTicker = jsonObject.getJSONObject("ticker");
        return jsonTicker.getDoubleValue("last");

    }

    public List<KLinePoint> getKLines(IndexConfig indexConfig) throws Exception {
        return getKLines(indexConfig, null);
    }

    public List<KLinePoint> getKLines(IndexConfig indexConfig, Integer size) throws Exception {
        // 返回值
        List<KLinePoint> kLinePoints = new ArrayList<KLinePoint>();

        // 期货行情信息
        String klineStr = iFutureGetApi.future_kline(indexConfig.getSymbol(), indexConfig.getContract_type().getKeyWord(),
                indexConfig.getTypes_Enum().getKeyWord(), size);

        // 字符串转换成Klines对象
        // 解析json 字符串
        JSONArray array = new JSONArray();
        try {
            array = JSONArray.parseArray(klineStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0; i < array.size(); i++) {

            KLinePoint kLinePoint = new KLinePoint();

            // 转换成数组
            JSONArray array_KLinePoint = array.getJSONArray(i);

            kLinePoint.setSymbol(indexConfig.getSymbol());
            kLinePoint.setType(indexConfig.getContract_type().getKeyWord());
            kLinePoint.setUnixTime(array_KLinePoint.getLongValue(0));
            kLinePoint.setOpen(array_KLinePoint.getDouble(1));
            kLinePoint.setHigh(array_KLinePoint.getDouble(2));
            kLinePoint.setLow(array_KLinePoint.getDouble(3));
            kLinePoint.setLast(array_KLinePoint.getDouble(4));
            kLinePoint.setVol(array_KLinePoint.getDouble(5));
            kLinePoint.setVolCoin(array_KLinePoint.getDouble(6));

            kLinePoints.add(kLinePoint);
        }

        return kLinePoints;
    }

    public void checkOrder(Order_Future order) throws IOException {
        String result = iFuturePostApi.future_userinfo_4fix();
        System.out.println(result);

    }

    public Order_Future getOrderInfo(String symbol, String orderId) throws IOException {

        Order_Future result_Order_Future = null;

        String resultJson = iFuturePostApi.future_order_info(symbol, "this_week", orderId, "", "", "");

        JSONObject jsonObject = JSONObject.parseObject(resultJson);
        String result = jsonObject.getString("result");
        if (result.equals("true")) {

            JSONArray jsonArray = jsonObject.getJSONArray("orders");

            if (jsonArray.size() > 0) {
                result_Order_Future = JSONObject.parseObject(jsonArray.get(jsonArray.size() - 1).toString(),
                        new TypeReference<Order_Future>() {
                        });
            }

        }
        return result_Order_Future;
    }

    public void addOrder(Order_Future order) throws IOException {

        String result = iFuturePostApi.future_trade(order.getSymbol(), "this_week", String.valueOf(order.getPrice()),
                String.valueOf(order.getAmount()), order.getType(), "0");
        System.out.println(result);

    }

    public void cancelOrder(String symbol, String orderId) throws IOException {
        // 现货撤销订单
        String resultJson = iFuturePostApi.future_cancel(symbol, "this_week", orderId);
        System.out.println(resultJson);
    }

    /**
     * 转币
     *
     * @param coinname
     * @param type
     * @param amount
     * @throws IOException
     */
    public boolean fund_devolve(String coinname, int type, double amount) throws IOException {
        String resultJson = iFuturePostApi.future_devolve(coinname, String.valueOf(type), String.valueOf(amount));

        JSONObject jsonObject = JSONObject.parseObject(resultJson);
        String result = jsonObject.getString("result");
        if (result.equals("true")) {
            return true;
        }
        return false;
    }

}
